package algorithm.exam.queue;

import java.util.Stack;

public class calculate {

    public int calculate(String s) {
        char[] array =s.toCharArray();
        Stack<Integer> nums =new Stack();
        int last=0;
        boolean flag=false;

        for(int i=0;i<array.length;i++){

            if (Character.isDigit(s.charAt(i))) {
                last = last * 10 + s.charAt(i) - '0';
            }else {
                if(!flag){
                    nums.push(last);
                }

                last=0;
                if('+'==array[i]){
                    continue;
                }
                if('-'==array[i]){
                    i++;
                    last=array[i]-'0';
                    continue;
                }
                if('*'==array[i]){
                    i++;
                    while (' '==array[i]){
                        i++;
                    }
                    while (i<array.length&&Character.isDigit(s.charAt(i))){
                        last =last * 10 + s.charAt(i) - '0';
                        i++;
                    }
                    int res =last*nums.pop();
                    nums.push(res);
                    continue;
                }
                if('/'==array[i]){
                    i++;
                    while (' '==array[i]){
                        i++;
                    }
                    while (i<array.length&&Character.isDigit(s.charAt(i))){
                        last =last * 10 + s.charAt(i) - '0';
                        i++;
                    }

                    int res=nums.pop()/last;
                    nums.push(res);
                    continue;
                }
                if(' '==array[i]){
                    flag=true;
                    continue;
                }



            }
        }

        nums.push(last);
        int sum=0;
        while(nums.size()!=0){
            sum=sum+nums.pop();
        }
        return sum;
    }

    public static void main(String[] args) {
        calculate calculate =new calculate();
        System.out.println(calculate.calculate(" 3+5 / 2 "));;
    }
}
